import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Button } from 'antd';
import { getMd5 } from '@/utils/utils';
import { getToken } from '@/utils/utils';
import { fingerprintFetch } from '@/utils/request';
import { getOptAuthHeaders } from '@/utils/common';

const mapStateToProps = (state: any) => ({});
class PdfView extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      showPdf: false,
      pdfDoc: null,
      file: {},
      pdfParams: {
        total: 0,
        pageNumber: 1,
      }
    };
  }

  componentDidMount () {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  initView = (file: any) => {
    this.setState({
      file,
    });
    this.loadFile(file);
  }

  clearData = () => {
    this.setState({
      showPdf: false,
      pdfDoc: null,
      file: {},
      pdfParams: {
        total: 0,
        pageNumber: 1,
      }
    })
  }

  loadFile = async (file: any) => {
    let pdfjs = await import('pdfjs-dist/build/pdf');
    let pdfjsWorker = await import('pdfjs-dist/build/pdf.worker.entry');
    pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
    if (file.fileExt === 'pdf') {
      const tempStr = decodeURIComponent(file.fileUrl);
      let md5 = getMd5('strUrl=' + tempStr);
      pdfjs.getDocument({
        url: `${window.g.url}/common/download?strUrl=` + file.fileUrl,
        httpHeaders: {
          shaSign: md5,
          ...getOptAuthHeaders(),
          'Optauthorization': `${getToken()}`,
        },
      }).promise.then((doc: any) => {
        this.setState({
          showPdf: true,
          pdfDoc: doc,
          pdfParams: {
            total: doc.numPages,
            pageNumber: 1,
          }
        }, () => {
          const { pdfParams: { total, pageNumber } } = this.state;
          this.getPdfPage(1);
        })
      })
    } else {
      const str = `${window.g.url}/common/convert2Pdf?strUrl=` + file.fileUrl;
      // let md5 = getMd5('strUrl=' + file.fileUrl);
      const tempStr = decodeURIComponent(file.fileUrl);
      let md5 = getMd5('strUrl=' + tempStr);
      const newOptions: any = {};
      newOptions.method = 'GET';
      newOptions.headers = {
        OptAuthorization: `${getToken()}`,
        shaSign: md5,
        'Content-Type': 'application/json;charset=utf-8',
      };
      fingerprintFetch(str, newOptions)
        .then(response => {
          if (response.status === 200) {
            return response.blob();
          } else {
            throw response;
          }
        })
        .then(blob => {
          if (blob) {
            const objectUrl = URL.createObjectURL(blob);
            pdfjs.getDocument(objectUrl).promise.then((doc: any) => {
              this.setState({
                showPdf: true,
                pdfDoc: doc,
                pdfParams: {
                  total: doc.numPages,
                  pageNumber: 1,
                }
              }, () => {
                const { pdfParams: { total, pageNumber } } = this.state;
                this.getPdfPage(1);
              })
            })
          }
        })
    }
  }

  getPdfPage = (number: number) => {
    const { pdfDoc } = this.state;
    if (pdfDoc) {
      pdfDoc.getPage(number).then((page: any) => {
        const viewport = page.getViewport();
        const canvas: any = document.getElementById('pdf-render');
        const context = canvas.getContext('2d');
        canvas.width = viewport.viewBox[2];
        canvas.height = viewport.viewBox[3];
        viewport.width = viewport.viewBox[2];
        viewport.height = viewport.viewBox[3];
        canvas.style.width = Math.floor(viewport.width) + 'px';
        canvas.style.height = Math.floor(viewport.height) + 'px';
        let renderContext = {
          canvasContext: context,
          viewport: viewport,
          // 这里transform的六个参数，使用的是transform中的Matrix(矩阵)
          transform: [1, 0, 0, -1, 0, viewport.height]
        }
        // 进行渲染
        page.render(renderContext)
      })
    }
  }

  // 上一页
  prevPage = () => {
    const { pdfDoc, pdfParams: { pageNumber, total } } = this.state;
    if (!pdfDoc) return;
    let tempPage = pageNumber;
    if(tempPage > 1) {
      tempPage -= 1
    } else {
      tempPage  = 1
    }
    this.setState({
      pdfParams: {
        pageNumber: tempPage,
        total: total
      }
    }, () => {
      this.getPdfPage(tempPage)
    })
  }

  //  下一页
  nextPage = () => {
    const { pdfDoc, pdfParams: { pageNumber, total } } = this.state;
    if (!pdfDoc) return;
    let tempPage = pageNumber;
    if(tempPage < total) {
      tempPage += 1
    } else {
      tempPage  = total
    }
    this.setState({
      pdfParams: {
        pageNumber: tempPage,
        total: total
      }
    }, () => {
      this.getPdfPage(tempPage)
    })
  }
  
  render() {
    const { pdfParams: { pageNumber, total }, file, fileUrl, showPdf } = this.state;
    return (
      <div style={{ width: '100%', height: '100%', inset: '32px 0 0', }}>
        <div style={{ width: '100%', height: '30px' }}>
          <span>{pageNumber} / {total}</span>
          <Button 
            type="default"
            disabled={ !showPdf || pageNumber == 1 }
            style={{
              marginLeft: '12px'
            }}
            onClick={(e) => {
              this.prevPage()
            }}
          >上一页</Button>
          <Button 
            type="default" 
            disabled={ !showPdf || pageNumber == total }
            style={{
              marginLeft: '12px'
            }} 
            onClick={(e) => {
              this.nextPage()
            }}
          >下一页</Button>
        </div>
        <canvas id="pdf-render" style={{ marginTop: '30px', marginLeft: 'auto', marginRight: 'auto' }}></canvas>
      </div>
    )
  }
}
export default connect(mapStateToProps)(PdfView);
// export default PdfView;
